var tls = require('tls'),
	fs = require('fs'),
	sys = require('sys'),
	http = require('http'),
	url = require('url');

// Tls Server
var options = {
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('cert.pem'),
    port: 8000
};

sys.puts("Tls server started.");

tls.createServer(options, function (socket)
{
    sys.puts("Tls connection established from: " + socket.remoteAddress);

	if(!fs.existsSync('peers'))
		fs.writeFileSync('peers', '[]', 'utf8');

    socket.addListener("data", function (data)
    { 
        sys.puts("Data received: " + data);

    	data = JSON.parse(data);

    	if(data.action == 'register')
    	{
    		fs.readFile('peers', 'utf8', function(err, peers)
			{
				if (err)	 
					return console.log(err);

				peers = JSON.parse(peers);

				var newPeer = {
					address: socket.remoteAddress,
					port: data.port
				};	

				if(peers.indexOf(newPeer) == -1)
				{
					peers.push(newPeer);

					fs.writeFile('peers',  JSON.stringify(peers) , 'utf8', function (err, data)
					{	  
						if (err)
							return console.log(err);
					});
				}

			});	    	
		}
		else if(data.action == 'upload')
		{
			fs.readFile('peers', 'utf8', function(err, peers)
			{
				if (err)		
					return console.log(err);

				socket.write(peers);
			});
		}
    });
}).listen(8000);
